package pro.softzhang.algo.lc0;

import pro.softzhang.algo.flag.book.BOfferS;
import pro.softzhang.algo.flag.knowledge.KBackTracking;
import pro.softzhang.algo.flag.x.XOptimal;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * 78. 子集
 * https://leetcode.cn/problems/subsets/description/
 */
@KBackTracking
@BOfferS
public class LC78_Subsets {
    public static void main(String[] args) {

    }

    /**
     * 
     */
    @XOptimal
    static
    class Solution {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> subsets = new ArrayList<>();
            subsets0(nums, 0, new LinkedList<>(), subsets);
            return subsets;
        }

        private void subsets0(int[] nums, int idx, LinkedList<Integer> subset, List<List<Integer>> subsets) {
            if(idx == nums.length) {
                subsets.add(new ArrayList<>(subset));
                return;
            }

            subsets0(nums, idx + 1, subset, subsets);
            subset.add(nums[idx]);
            subsets0(nums, idx + 1, subset, subsets);
            subset.removeLast();
        }
    }

    /**
     * 子集型回溯 第二种
     */
    static
    class Solution1 {
        public List<List<Integer>> subsets(int[] nums) {
            List<List<Integer>> answer = new ArrayList<>();
            dfs(0, nums, new LinkedList<>(), answer);
            return answer;
        }

        private void dfs(int i, int[] nums, LinkedList<Integer> path, List<List<Integer>> answer) {
            answer.add(new ArrayList<>(path));
            if(i == nums.length) {
                return;
            }

            for(int j = i; j < nums.length; j++) {
                path.add(nums[j]);
                dfs(j + 1, nums, path, answer);
                path.removeLast();
            }
        }
    }
}
